package org.alanlau.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author liukun
 * @version 1.0
 * @date 2021/3/3 10:10
 */
public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler> {
    @Override
    public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) {
        // 这里之所以要再次调用 accept() 方法，是因为一个 AsynchronousServerSocketChannel 可以接收程前上万个客户端，所以需要继续调用它的 accept方法，接收其他的客户端连接，最终形成一个循环
        // 每当接收一个客户读连接成功之后，再异步接收新的客户端连接
        attachment.asynchronousServerSocketChannel.accept(attachment, this);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        result.read(buffer, buffer, new ReadCompletionHandler(result));
    }

    @Override
    public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
        exc.printStackTrace();
        attachment.latch.countDown();
    }
}
